import qs from "querystring";
import CacheUtils from "@/utils/CacheUtils";
import Modal from "@/utils/Modal";

class HttpRequest {
    constructor(baseUrl = process.env.VUE_APP_URL) {
        this.baseUrl = baseUrl || '';
    }

    static async _login() {
        await Modal.toast("登录失效请重新登录！");
        await uni.redirectTo({
            url: '/pages/login/index'
        })
    }

    static _responseInterceptor(response, resolve, reject, option) {
        if (response.statusCode !== 200) {
            switch (response.statusCode) {
                case 400:
                    Modal.toast("请求参数错误！");
                    break;
                case 404:
                    Modal.toast("接口不存在！");
                    break;
                case 500:
                    Modal.toast("服务器错误！");
                    break;
                default:
                    Modal.toast("网络异常,请检查网络", {position: "bottom"});
                    break;
            }
            reject(response);
            return;
        }

        if (response.data.error) {
            if (response.data.code == 401 || response.data.code == 300) {
                CacheUtils.deleteCache('token');
                CacheUtils.deleteCache('sessionId');
                CacheUtils.deleteCache('user');
                HttpRequest._login();
                reject(response.data.message);
                return;
            }
            reject(response.data.message);
            return;
        }
        resolve(response.data.data);
    }

    request(option) {
        option = Object.assign({method: "GET", header: {}}, option);
        if (option.params) {
            let prefix = option.url.includes('?') ? '&' : '?';
            option.url += `${prefix}${qs.stringify(option.params)}`;
        }
        option.header['X-Requested-With'] = 'XMLHttpRequest';
        let token = CacheUtils.getCache("token");
        if (token) {
            option.header.Token = token;
        }
        let finalURL = option.url.startsWith("http") ? option.url : (this.baseUrl + option.url);
        return new Promise((resolve, reject) => {
            uni.request({
                ...option,
                url: finalURL,
                complete: (res) => {
                    HttpRequest._responseInterceptor(res, resolve, reject, option);
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }

    /**
     * 发起一个GET请求
     * @param {String} url 请求地址
     * @param {Object?} params 地址栏中需要的参数
     * @returns {Promise<unknown>}
     */
    get(url, params = null) {
        return this.request({url, params, method: "GET"});
    }

    /**
     * 发起一个POST请求
     * @param {String} url 要请求的地址
     * @param {Object?} data 请求体中的参数
     * @param {Object?} params 地址栏中需要的参数
     * @returns {Promise<unknown>}
     */
    post(url, data = {}, params = null) {
        return this.request({url, params, data, method: "POST"});
    }
}

export default new HttpRequest();
